package com.jinlejia.erp.ui.mine.transfer;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.TransferBean;
import com.jinlejia.erp.databinding.ActivityTransferApplyDepartmentBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 异动申请-选择部门
 */
public class TransferApplyDepartmentActivity extends AppCompatActivity {
    private TransferBean bean;
    //异动前职务等级
    private String userLevel;
    //异动后职务
    private String level;

    private ProgressDialog progressDialog;

    private ActivityTransferApplyDepartmentBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_transfer_apply_department);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initData() {
        progressDialog = new ProgressDialog(this, "加载中...");
        bean = ((TransferBean) getIntent().getSerializableExtra("bean"));
        userLevel = getIntent().getStringExtra("userLevel");
        level = getIntent().getStringExtra("level");
        if (!"2".equals(level) && ("带训经理".equals(bean.getLeaderDutyName())||bean.getLeaderDutyName().contains("D"))) {//异动的直属上级是D/FD，无论有没有ss/sc时，都能显示出所对应的共享店
            binding.llShopall.setVisibility(View.VISIBLE);
            binding.llShopall.setClickable(false);
            binding.tvShop.setText(bean.getLeaderStoreName());
            binding.llShopall.setBackgroundColor(Color.parseColor("#e1e1e1"));
            binding.llShop.setBackgroundColor(Color.parseColor("#e1e1e1"));
            bean.setNewShareStoreName(bean.getLeaderStoreName());
            bean.setNewShareStoreCode(bean.getLeaderStoreCode());
        } else if ("2".equals(level) || "1".equals(level)) {//当异动人异动后职务是带训经理或合作人（实习期合作人、储备合作人、合作人、复活期合作人）时，需要填写其所属共享店
            binding.llShopall.setVisibility(View.VISIBLE);
            binding.llShopall.setClickable(true);
            binding.llShopall.setBackgroundColor(Color.parseColor("#F4F4F4"));
            binding.llShop.setBackgroundColor(Color.parseColor("#FFFFFF"));
        } else {
            binding.llShopall.setVisibility(View.GONE);
        }
    }

    private void initView() {
        formatStr(binding.dmt, "*");
        formatStr(binding.tvShops, "*");
    }

    private Intent mIntent;

    private int checkId = -1;

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_department:
                //异动后的行政部门
                mIntent = new Intent(TransferApplyDepartmentActivity.this, TransferCheckActivity.class);
                mIntent.putExtra("type", "3");
                mIntent.putExtra("checkId", checkId);
                startActivityForResult(mIntent, 3001);
                break;
            case R.id.ll_shopall:
                //异动后所属共享店
                mIntent = new Intent(TransferApplyDepartmentActivity.this, TransferApplySearchShopActivity.class);
                mIntent.putExtra("parentPin", bean.getNewLeaderPin());//直属上级pin
                startActivityForResult(mIntent, 3002);
                break;
            case R.id.bt_pre:
                //上一步
                releaceData();
                finish();
                break;
            case R.id.bt_commit:
                //提交
                checkData();
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    /**
     * 校验
     */
    private void checkData() {
        if (TextUtils.isEmpty(binding.tvDepartment.getText().toString())) {
            CustomToast.showToast(TransferApplyDepartmentActivity.this, "请选择异动后的行政部门", 1500);
        } else if (binding.llShopall.getVisibility() == View.VISIBLE && TextUtils.isEmpty(binding.tvShop.getText().toString())) {
            CustomToast.showToast(TransferApplyDepartmentActivity.this, "请选择所属共享店", 1500);
        } else {
            pushData();
        }
    }

    private JSONObject jsonObject = new JSONObject();

    /**
     * 提交异动申请
     */
    private void pushData() {
        progressDialog.show();
        jsonObject.put("userbdTypeName", bean.getUserbdTypeName());
        jsonObject.put("userbdTypeCode", bean.getUserbdTypeCode());
        jsonObject.put("remark", bean.getRemark());
        jsonObject.put("newDutyCode", bean.getNewDutyCode());
        jsonObject.put("newDutyName", bean.getNewDutyName());
        jsonObject.put("transferType", bean.getTransferType());
        jsonObject.put("newDeptId", bean.getNewDeptId());//所属部门id
        jsonObject.put("newDeptName", bean.getNewDeptName());//所属部门名称
        if (!TextUtils.isEmpty(getIntent().getStringExtra("newTrainingFlag"))){
            jsonObject.put("trainingFlag",getIntent().getStringExtra("newTrainingFlag"));//带训标识
        }

        if (!"".equals(bean.getRecruitPin()) && null != bean.getRecruitPin())
            jsonObject.put("recruitPin", bean.getRecruitPin());//招募人pin
        if (!"".equals(bean.getNewLeaderPin()) && null != bean.getNewLeaderPin())
            jsonObject.put("newLeaderPin", bean.getNewLeaderPin());//直属上级pin
        if (!"".equals(bean.getNewShareStoreCode()) && null != bean.getNewShareStoreCode())
            jsonObject.put("newShareStoreCode", bean.getNewShareStoreCode());//共享店编码
        if (!"".equals(bean.getNewShareStoreName()) && null != bean.getNewShareStoreName())
            jsonObject.put("newShareStoreName", bean.getNewShareStoreName());//共享店名称
        if (!"".equals(bean.getHrQuDao()) && null != bean.getHrQuDao())
            jsonObject.put("recruitChannel", bean.getHrQuDao());//招募渠道

        OkHttpUtils
                .postString()
                .url(ApiConfig.TRANSFER_CONFIRM)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(TransferApplyDepartmentActivity.this, response, null)) {
                            mIntent = new Intent(TransferApplyDepartmentActivity.this, CommitSuccessActivity.class);
                            startActivity(mIntent);
                        } else {
                            String message = response.get("message").toString();
                            CustomToast.showToast(TransferApplyDepartmentActivity.this, message, 1500);
                        }
                    }
                });
    }

    private void formatStr(TextView view, String word) {
        String tmp = "<font color=\"red\">" + word + "</font>";
        String str = view.getText().toString().replace(word, tmp);
        //Html.fromHtml(str)
        view.setText(Html.fromHtml(str));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3001) {
                binding.tvDepartment.setText(data.getStringExtra("name"));
                checkId = data.getIntExtra("checkId", -1);
                bean.setNewDeptId(data.getStringExtra("code"));
                bean.setNewDeptName(data.getStringExtra("name"));
            } else if (requestCode == 3002) {
                String shareStoreCode = data.getStringExtra("shareStoreCode");
                String shareStoreName = data.getStringExtra("shareStoreName");
                bean.setNewShareStoreCode(shareStoreCode);
                bean.setNewShareStoreName(shareStoreName);
                binding.tvShop.setText(shareStoreName);
            }
        }
    }

    @Subscriber
    public void onEvent(TransferApplySuccessEvent event) {
        if (event.getResult() == 0) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        releaceData();
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void releaceData() {
        bean.setNewShareStoreName("");//共享店
        bean.setNewShareStoreCode("");//共享店
        bean.setNewDeptId("");//部门id
        bean.setNewDeptName("");//部门name
    }


}
